﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using EDXLCoT;
using EDXLSharp;
using EDXLSharp.EDXLDELib;
using ICNETServices;

namespace ICNETDAL
{
  public class RSSDal
  {
    public static List<SyndicationItem> GetAllRSSItems()
    {
      List<SyndicationItem> synItems = new List<SyndicationItem>();

      RSSDataContext linqDB = new RSSDataContext(ICNETSOAConstants.RSSConnectionString);
      List<RSS> items = (from p in linqDB.RSSes
                         select p).ToList<RSS>();

      if (items != null)
      {
        foreach (RSS item in items)
        {

          SyndicationItem synItem = SyndicationItem.Load(item.RSSBody.CreateReader());

          Status stat = (from s in linqDB.Status
                         where s.RSSId == item.RSSId
                         orderby s.Updated descending
                         select s).FirstOrDefault();

          if (stat != null)
          {
            synItem.ElementExtensions.Add("statusvalue", ICNETSOAConstants.ICNETNamespace, stat.Value.ToString());
            synItem.ElementExtensions.Add("statusdescription", ICNETSOAConstants.ICNETNamespace, stat.Description);
          }

          synItems.Add(synItem);
        }
      }
        
      return synItems;
    }


    public static void SaveRSSItem(XElement xe)
    {
      SyndicationItem synItem = SyndicationItem.Load(xe.CreateReader());

      if (synItem != null)
      {
        RSS rss = new RSS();
        rss.RSSBody = xe;
        rss.RSSId = synItem.Id;
        rss.LastUpdated = synItem.LastUpdatedTime.LocalDateTime;

        RSSDataContext linqDB = new RSSDataContext(ICNETSOAConstants.RSSConnectionString);
        linqDB.RSSes.InsertOnSubmit(rss);
        linqDB.SubmitChanges();
      }
      else
      {
        //throw System.ArgumentException;
      }
    }

    public static void SaveStatus(XElement xe)
    {
      string rssId = xe.Element("rssid") == null ? "" : xe.Element("rssid").Value;
      int statusVal = Int32.Parse(xe.Element("status") == null ? "0" : xe.Element("status").Value);
      string statusDesc = xe.Element("desc") == null ? "" : xe.Element("desc").Value;

      RSSDataContext linqDB = new RSSDataContext(ICNETSOAConstants.RSSConnectionString);
      int rssTableId = (from p in linqDB.RSSes
                        where p.RSSId == rssId
                        select p.Id).SingleOrDefault();

      Status status = new Status();
      status.RSSId = rssId;
      status.Value = statusVal;
      status.Description = statusDesc;
      status.Updated = DateTime.Now;

      linqDB.Status.InsertOnSubmit(status);
      linqDB.SubmitChanges();
    }

    public static void SaveDE(XElement xe)
    {
      try
      {
        EDXLDE de = new EDXLDE(xe.ToString());
        List<IGeoRSS> georssList = DEDalUtils.UnboxContentObjectsForGeoRSS(de);
        List<SyndicationItem> synList = null;
        Guid someGuid = new Guid();
        RSSDataContext linqDB = new RSSDataContext(ICNETSOAConstants.RSSConnectionString);


        foreach (IGeoRSS georss in georssList)
        {
          synList = new List<SyndicationItem>();
          georss.ToGeoRSS(synList, someGuid);

          foreach (SyndicationItem synItem in synList)
          {
            //SyndicationItem myitem = new SyndicationItem();
            //myitem.Authors.Add(new SyndicationPerson(de.SenderID, de.SenderID, String.Empty));
            //myitem.Categories.Add(new SyndicationCategory(EDXLConstants.SitRepSyndicationCategoryName, EDXLConstants.SyndicationCategoryScheme, EDXLConstants.SyndicationCategoryLabel));
            //myitem.Title = new TextSyndicationContent(EDXLConstants.SitRepSyndicationTitle + " " + linkUID.ToString());
            //this.report.ToGeoRSS(myitem);
            //this.reportLocation.ToGeoRSS(myitem);
            //myitem.Copyright = new TextSyndicationContent(EDXLConstants.SyndicationCopyright);
            //myitem.LastUpdatedTime = this.fromDateTime;
            //myitem.Links.Add(new SyndicationLink(new Uri(EDXLConstants.SyndicationLinkBaseURI + "SitRep/" + linkUID.ToString())));
            //myitem.PublishDate = DateTime.Now;
            //myitem.Summary = new TextSyndicationContent("MessageID: " + this.messageID);

            //myitem.ElementExtensions.Add("expire_time", "", this.ToDateTime.ToUniversalTime().ToString());

            //myitems.Add(myitem);
            try
            {
 
              StringBuilder sb = new StringBuilder();

              XmlWriter xWriter = XmlWriter.Create(sb);
              synItem.SaveAsAtom10(xWriter);
              xWriter.Close();

              RSS rss = new RSS();
              rss.RSSBody = XElement.Parse(sb.ToString());
              rss.RSSId = string.IsNullOrWhiteSpace(synItem.Id) ? de.DistributionID : synItem.Id;
              rss.LastUpdated = synItem.LastUpdatedTime.LocalDateTime;
              
              linqDB.RSSes.InsertOnSubmit(rss);
              
            }
            catch
            {
              throw;
            }
          }
        }

        linqDB.SubmitChanges();
        
      }
      catch (Exception Ex)
      {
        throw Ex;
      }
    }
  }
}
